<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="制造商" prop="manufacturer">
        <el-input v-model="queryParams.manufacturer"
                  placeholder="请输入制造商"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="queryParams.model"
                  placeholder="请输入型号"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="绑定用户" prop="nickName">
        <el-input v-model="queryParams.params.nickName"
                  placeholder="请输入用户"
                  clearable
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="设备状态" clearable>
          <el-option v-for="dict in dict.type.bus_equip_status"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="在线状态" prop="online">
        <el-select v-model="queryParams.online" placeholder="在线状态" clearable>
          <el-option v-for="dict in dict.type.bus_equip_online_status"
                     :key="dict.value"
                     :label="dict.label"
                     :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="生产日期">
        <el-date-picker v-model="daterangeManufactureDate"
                        style="width: 240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="激活时间">
        <el-date-picker
          v-model="daterangeActivationTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="损坏时间">
        <el-date-picker
          v-model="daterangeDamageTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:equipment:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['business:equipment:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:equipment:export']"
        >导出
        </el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column v-if="columns[0].visible" align="center" label="绑定用户" prop="params.nickName"/>
      <el-table-column v-if="columns[1].visible" align="center" label="设备名称" prop="name"/>
      <el-table-column v-if="columns[2].visible" align="center" label="序列号" prop="serialNum" show-overflow-tooltip/>
      <el-table-column v-if="columns[3].visible" align="center" label="MAC" prop="mac" width="150"/>
      <el-table-column v-if="columns[4].visible" align="center" label="制造商" prop="manufacturer"/>
      <el-table-column v-if="columns[5].visible" align="center" label="型号" prop="model"/>
      <el-table-column v-if="columns[6].visible" align="center" label="在线状态" key="online">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.online"
            active-value="1"
            inactive-value="0"
            @change="handleOnlineChange(scope.row)"
            :disabled="scope.row.status !== 1"
            v-hasPermi="['business:equipment:power']"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[7].visible" align="center" label="设备状态" prop="status">
        <template slot-scope="scope">
<!--          <el-tooltip v-if="scope.row.status >= 0" :content="scope.row.status === 0 ? '点击激活' : '点击维修'">
            <el-button type="text" @click="activationDialog(scope.row)">
              <dict-tag :options="dict.type.bus_equip_status" :value="scope.row.status"/>
            </el-button>
          </el-tooltip>-->
          <el-tooltip v-if="scope.row.status === 0" content="点击激活">
            <el-button type="text" @click="activationDialog(scope.row)">
              <dict-tag :options="dict.type.bus_equip_status" :value="scope.row.status"/>
            </el-button>
          </el-tooltip>
          <label v-else>
            <dict-tag :options="dict.type.bus_equip_status" :value="scope.row.status" disabled="disabled"/>
          </label>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[8].visible" align="center" label="生产日期" prop="manufactureDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[9].visible" align="center" label="激活时间" prop="activationTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activationTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[10].visible" align="center" label="激活码" prop="activationCode"
                       show-overflow-tooltip
      />
      <el-table-column v-if="columns[11].visible" align="center" label="在线时长" prop="runtimeCount"/>
      <el-table-column v-if="columns[12].visible" align="center" label="损坏时间" prop="damageTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.damageTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns[13].visible" align="center" label="备注" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-1"
            @click="detailDialog(scope.row)"
            v-hasPermi="['business:equipment:detail']"
          >详情
          </el-button>
          <el-button
            v-show="false"
            size="mini"
            type="text"
            icon="el-icon-edit"
            :options="dict.type.bus_equip_status"
            @click="handleUpdate(scope.row, dict.type.bus_equip_status)"
            v-hasPermi="['business:equipment:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:equipment:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="maintenanceDialog(scope.row)"
            v-hasPermi="['business:equipment:remove']"
          >维修
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制造商" prop="manufacturer">
              <el-input v-model="form.manufacturer" placeholder="请输入制造商"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="MAC" prop="mac">
              <el-input v-model="form.mac" placeholder="请输入MAC"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="生产日期" prop="manufactureDate">
              <el-date-picker clearable
                              v-model="form.manufactureDate"
                              type="date"
                              disabled
                              value-format="yyyy-MM-dd"
                              placeholder="请选择生产日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model="form.statusValue" placeholder="请选择设备状态">
                <el-option
                  v-for="dict in dict.type.bus_equip_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                  :aria-selected="form.status === dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="激活时间" prop="manufactureDate">
              <el-date-picker clearable
                              v-model="form.activationTime"
                              type="datetime"
                              disabled
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请激活"
              ></el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="激活码" prop="activationCode">
              <el-input v-model="form.activationCode" placeholder="请获取激活码" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button plain>获取</el-button>
          </el-col>
          <el-col :span="3">
            <el-button plain>复制</el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 激活设备对话框 -->
    <el-dialog :title="activation.title" :visible.sync="activation.open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="制造商">
              <el-input v-model="form.manufacturer" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称">
              <el-input v-model="form.name" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="型号">
              <el-input v-model="form.model" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="序列号">
              <el-input v-model="form.serialNum" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="绑定用户">
              <el-select v-model="form.userId" filterable placeholder="请选择">
                <el-option
                  v-for="item in sysUserList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>


      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleActivation">激 活</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设备导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary"
                   :underline="false"
                   style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listEquipment,
  getEquipment,
  delEquipment,
  addEquipment,
  updateEquipment,
  startEquipment,
  stopEquipment, activationEquit
} from '@/api/business/equipment'
import { getUserIdNameList } from '@/api/system/user'
import { getToken } from '@/utils/auth'

export default {
  name: 'Equipment',
  dicts: ['bus_equip_status', 'bus_equip_online_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      equipmentList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeManufactureDate: [],
      // 备注时间范围
      daterangeActivationTime: [],
      // 备注时间范围
      daterangeDamageTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        serialNum: null,
        name: null,
        manufacturer: null,
        model: null,
        mac: null,
        online: null,
        status: null,
        manufactureDate: null,
        activationTime: null,
        runtimeCount: null,
        activationCode: null,
        damageTime: null,
        params: {
          nickName: null
        }
      },
      // 列信息
      columns: [
        { key: 0, label: `绑定用户`, visible: true },
        { key: 1, label: `设备名称`, visible: true },
        { key: 2, label: `序列号`, visible: true },
        { key: 3, label: `MAC`, visible: false },
        { key: 4, label: `制造商`, visible: false },
        { key: 5, label: `型号`, visible: true },
        { key: 6, label: `在线状态`, visible: true },
        { key: 7, label: `设备状态`, visible: true },
        { key: 8, label: `生产日期`, visible: true },
        { key: 9, label: `激活时间`, visible: true },
        { key: 10, label: `激活码`, visible: true },
        { key: 11, label: `在线时长`, visible: false },
        { key: 12, label: `损坏时间`, visible: false },
        { key: 13, label: `备注`, visible: true }
      ],
      // 表单参数
      form: {},
      // 导入参数
      upload: {
        // 是否显示弹出层（设备导入）
        open: false,
        // 弹出层标题（设备导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/equipment/importData'
      },
      activation: {
        open: false,
        title: '',
        headers: { Authorization: 'Bearer ' + getToken() },
        url: process.env.VUE_APP_BASE_API + '/system/equipment/activation'
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        manufacturer: [
          { required: true, message: '制造商不能为空', trigger: 'blur' }
        ],
        model: [
          { required: true, message: '型号不能为空', trigger: 'blur' }
        ],
        mac: [
          { required: true, message: 'MAC地址不能为空', trigger: 'blur' }
        ],
        online: [
          { required: true, message: '在线状态不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '设备状态不能为空', trigger: 'change' }
        ],
        manufactureDate: [
          { required: true, message: '生产日期不能为空', trigger: 'blur' }
        ],
        runtimeCount: [
          { required: true, message: '总在线时长, 单位: s不能为空', trigger: 'blur' }
        ]
      },
      sysUserList: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询设备列表 */
    getList() {
      this.loading = true
      if (null != this.daterangeManufactureDate && '' !== this.daterangeManufactureDate) {
        this.queryParams.params['beginManufactureDate'] = this.daterangeManufactureDate[0]
        this.queryParams.params['endManufactureDate'] = this.daterangeManufactureDate[1]
      }
      if (null != this.daterangeActivationTime && '' !== this.daterangeActivationTime) {
        this.queryParams.params['beginActivationTime'] = this.daterangeActivationTime[0]
        this.queryParams.params['endActivationTime'] = this.daterangeActivationTime[1]
      }
      if (null != this.daterangeDamageTime && '' !== this.daterangeDamageTime) {
        this.queryParams.params['beginDamageTime'] = this.daterangeDamageTime[0]
        this.queryParams.params['endDamageTime'] = this.daterangeDamageTime[1]
      }
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.activation.open = false
      this.upload.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        pageNum: 1,
        pageSize: 10,
        id: null,
        userId: null,
        serialNum: null,
        name: null,
        manufacturer: null,
        model: null,
        mac: null,
        online: null,
        status: null,
        manufactureDate: null,
        activationTime: null,
        runtimeCount: null,
        activationCode: null,
        damageTime: null,
        params: {
          nickName: null
        }
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeManufactureDate = []
      this.daterangeActivationTime = []
      this.daterangeDamageTime = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加设备'
    },
    /** 修改按钮操作 */
    handleUpdate(row, dict) {
      this.reset()
      const id = row.id || this.ids
      getEquipment(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改设备'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEquipment(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addEquipment(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除设备编号为"' + ids + '"的数据项？').then(function() {
        return delEquipment(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '设备导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/equipment/importTemplate', {}, `equipment_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/equipment/export', {
        ...this.queryParams
      }, `equipment_${new Date().getTime()}.xlsx`)
    },
    handleCommand(row) {
      this.$message('click on item ' + row)
    },
    // 设备在线状态修改
    handleOnlineChange(row) {
      if (row.status !== 1) {
        this.$modal.msgError('设备暂时不能使用')
        return
      }

      let off = row.online === '1'
      let text = off ? '开机' : '关机'
      this.$modal.confirm('确认要 ' + text + ' 吗？').then(function() {
        if (off) {
          return startEquipment(row.id)
        } else {
          return stopEquipment(row.id)
        }
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.online = row.online === '0' ? '1' : '0'
      })
    },
    // 设备激活对话框
    activationDialog(row) {
      this.reset()
      getUserIdNameList().then(resp => {
        this.sysUserList = resp.data
      })
      const id = row.id
      getEquipment(id).then(response => {
        this.form = response.data
        this.activation.open = true
        this.activation.title = '激活设备'
      })
    },
    // 激活设备
    handleActivation() {
      const form = this.form
      this.$modal.confirm('是否已确认设备及绑定用户信息无误？').then(function() {
        return activationEquit(form.id, form.userId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('激活成功')
      }).catch((err) => {
      })
    },
    // 设备维修对话框
    maintenanceDialog(row){
      this.$message({
        message: '暂未开放',
        center: true,
        type: 'error'
      });
    },
    // 设备详情对话框
    detailDialog(row){
      this.$message({
        message: '暂未开放',
        center: true,
        type: 'error'
      });
    }
  }
}
</script>
